import sys
from pathlib import Path
import json
import time
from typing import Dict, Any, Optional, Tuple, Union

# 添加必要的路径
sys.path.append(str(Path(__file__).parent.parent))
from reqapi.login.get_device_fingerprint import get_device_fingerprint_info
from reqapi.login.auth_integrated_login import AuthIntegratedLogin
from reqapi.user_info_api import UserInfoApi


class LoginManager:
    """登录管理类，提供登录相关功能"""
    
    def __init__(self, device_info_file: str = None, force_new_device: bool = True):
        """初始化登录管理类
        
        Args:
            device_info_file: 设备信息文件路径，默认为None，将根据手机号生成
            force_new_device: 是否强制生成新的设备信息，默认为False
        """
        self.device_info_file = device_info_file
        self.force_new_device = force_new_device
        self.android_id = None
        self.device_id = None
        self.uk = None
        self.auth_login = None
        self.mobile = None
        
        # 初始化设备信息将在发送验证码时进行
    
    def _init_device_info(self, mobile: str) -> bool:
        """初始化设备信息
        
        Args:
            mobile: 手机号码，用于生成设备信息文件名
            
        Returns:
            bool: 初始化是否成功
        """
        try:
            # 保存手机号
            self.mobile = mobile
            
            # 获取设备指纹信息
            self.android_id, self.device_id, self.uk = get_device_fingerprint_info(
                generate_new=self.force_new_device,
                file_path=self.device_info_file,
                mobile=mobile
            )
            
            if not self.device_id or not self.uk:
                print("获取设备指纹信息失败，无法初始化登录服务")
                return False
            
            # 初始化登录服务
            self.auth_login = AuthIntegratedLogin(device_id=self.device_id, uk=self.uk)
            return True
        except Exception as e:
            print(f"初始化设备信息失败: {e}")
            return False
    
    def send_sms_code(self, mobile: str, area: str = "86") -> Union[str, Tuple[str, str], None]:
        """发送短信验证码
        
        Args:
            mobile: 手机号码
            area: 区号，默认为中国区号86
            
        Returns:
            Union[str, Tuple[str, str], None]: 
                如果发送成功，返回成功提示信息
                如果需要上行短信，返回(上行短信内容, 上行短信号码)元组
                如果发送失败，返回None
        """
        if not self.auth_login:
            if not self._init_device_info(mobile):
                return None
        
        try:
            # 发送短信验证码
            result = self.auth_login.send_sms_code(mobile, area)
            return result
        except Exception as e:
            print(f"发送短信验证码失败: {e}")
            return None
    
    def login_with_sms_code(self, mobile: str, code: str, area: str = "86") -> Dict[str, Any]:
        """使用短信验证码登录
        
        Args:
            mobile: 手机号码
            code: 短信验证码
            area: 区号，默认为中国区号86
            
        Returns:
            Dict[str, Any]: 登录成功后的用户信息，包括token、昵称等，如果登录失败则返回空字典
        """
        if not self.auth_login:
            if not self._init_device_info(mobile):
                return {}
        
        try:
            # 使用短信验证码登录
            user_info = self.auth_login.login_with_sms_code(mobile, code, area)
            
            # 将设备ID和UK添加到用户信息中，确保后续API调用能使用
            if user_info:
                if 'device_id' not in user_info:
                    user_info['device_id'] = self.device_id
                if 'uk' not in user_info:
                    user_info['uk'] = self.uk
                    
                # 获取完整的用户信息
                self._get_complete_user_info(user_info)
            
            return user_info
        except Exception as e:
            print(f"短信验证码登录失败: {e}")
            return {}
    
    def login_with_sms_up(self, mobile: str, area: str = "86") -> Dict[str, Any]:
        """使用短信上行登录
        
        Args:
            mobile: 手机号码
            area: 区号，默认为中国区号86
            
        Returns:
            Dict[str, Any]: 登录成功后的用户信息，包括token、昵称等，如果登录失败则返回空字典
        """
        if not self.auth_login:
            if not self._init_device_info(mobile):
                return {}
        
        try:
            # 使用短信上行登录
            user_info = self.auth_login.login_with_sms_up(mobile, area)
            
            # 将设备ID和UK添加到用户信息中，确保后续API调用能使用
            if user_info:
                if 'device_id' not in user_info:
                    user_info['device_id'] = self.device_id
                if 'uk' not in user_info:
                    user_info['uk'] = self.uk
                    
                # 获取完整的用户信息
                self._get_complete_user_info(user_info)
            
            return user_info
        except Exception as e:
            print(f"短信上行登录失败: {e}")
            return {}
            
    def _get_complete_user_info(self, user_info: Dict[str, Any]) -> None:
        """获取完整的用户信息
        
        Args:
            user_info: 登录成功后的基本用户信息
        """
        try:
            # 提取必要的信息用于API调用
            device_id = user_info.get('device_id')
            auth_token = user_info.get('token')
            uk = user_info.get('uk')
            
            if not all([device_id, auth_token, uk]):
                print("缺少必要的用户信息，无法获取完整用户信息")
                return
                
            print(f"\n正在获取用户的完整信息...")
            
            # 创建用户信息API实例
            user_info_api = UserInfoApi(
                device_token=device_id,
                device_id=device_id,
                auth_token=auth_token,
                uk=uk
            )
            
            # 调用API获取完整用户信息
            complete_user_info = user_info_api.get_user_info()
            
            if complete_user_info:
                print("成功获取完整用户信息")
                
                # 将完整用户信息添加到user_info中
                user_info['complete_user_info'] = {
                    'userId': complete_user_info.UserId,
                    'nickName': complete_user_info.NickName,
                    'mobile': complete_user_info.Mobile,
                    'balance': complete_user_info.Balance,
                    'steamId': complete_user_info.SteamId,
                    'steamTradeStatusTip': complete_user_info.SteamTradeStatusTip,
                    'avatar': complete_user_info.Avatar,
                    'vipIconUrl': complete_user_info.vipIconUrls[0].iconConfig if complete_user_info.vipIconUrls and len(complete_user_info.vipIconUrls) > 0 else ''
                }
                
                # 更新基本用户信息
                if not user_info.get('nickname') and complete_user_info.NickName:
                    user_info['nickname'] = complete_user_info.NickName
                    
                if not user_info.get('steam_id') and complete_user_info.SteamId:
                    user_info['steam_id'] = complete_user_info.SteamId
                    
                if not user_info.get('avatar') and complete_user_info.Avatar:
                    user_info['avatar'] = complete_user_info.Avatar
                
                # 打印部分关键信息
                print(f"用户昵称: {complete_user_info.NickName}")
                print(f"手机号: {complete_user_info.Mobile}")
                print(f"余额: {complete_user_info.Balance}")
                print(f"Steam ID: {complete_user_info.SteamId}")
                print(f"Steam交易状态: {complete_user_info.SteamTradeStatusTip}")
            else:
                print("获取完整用户信息失败")
                
        except Exception as e:
            print(f"获取完整用户信息时出错: {e}")


# 使用示例
def login_example():
    """登录示例"""
    # 创建登录管理器实例
    login_manager = LoginManager()
    
    # 手机号码
    mobile = "13186793939"  # 替换为实际手机号
    
    # 发送短信验证码
    result = login_manager.send_sms_code(mobile)
    
    if isinstance(result, tuple):
        # 需要上行短信
        sms_content, sms_number = result
        print(f"请发送短信内容 '{sms_content}' 到号码 {sms_number}")
        
        # 等待用户发送短信
        time.sleep(5)  # 实际应用中可能需要更长的等待时间或其他机制
        
        # 使用短信上行登录
        user_info = login_manager.login_with_sms_up(mobile)
        if user_info:
            print("短信上行登录成功！")
            print(f"用户昵称: {user_info.get('nickname', '')}")
            print(f"登录令牌: {user_info.get('token', '')[:30]}...")
            return user_info
    elif result:
        # 短信验证码发送成功，这里模拟用户输入验证码
        # 实际应用中，需要从其他渠道获取验证码
        code = "123456"  # 替换为实际验证码
        
        # 使用短信验证码登录
        user_info = login_manager.login_with_sms_code(mobile, code)
        if user_info:
            print("短信验证码登录成功！")
            print(f"用户昵称: {user_info.get('nickname', '')}")
            print(f"登录令牌: {user_info.get('token', '')[:30]}...")
            return user_info
    
    print("登录失败")
    return None


if __name__ == "__main__":
    login_example()
